
package com.vanda.util;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.util.List;

import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.Converter;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.validator.GenericValidator;
/*******
 * 类说明:
 * 改写的BeanUtils类
 * <P>@author wkf3915
 * <P>@version 1.0 2005-3-10
 */
public class VandaBeanUtils extends org.apache.commons.beanutils.BeanUtils {
	static {
//		ConvertUtils.register(new VandaSqlDateConverter(), java.sql.Date.class);
//		ConvertUtils.register(new VandaStringConverter(), String.class);
	}
	public static void copyProperties(Object dest, Object orig)
		throws IllegalAccessException, InvocationTargetException {
		
		copyProperties(dest,orig,null);
	}
	
	public static void copyProperties(Object dest, Object orig,List names)
		throws IllegalAccessException, InvocationTargetException {
		// Validate existence of the specified beans
		if (dest == null) {
			throw new IllegalArgumentException("No destination bean specified");
		}
		if (orig == null) {
			throw new IllegalArgumentException("No origin bean specified");
		}
		// Copy the properties, converting as necessary
		PropertyDescriptor origDescriptors[] =
			PropertyUtils.getPropertyDescriptors(orig);
		for (int i = 0; i < origDescriptors.length; i++) {
			String name = origDescriptors[i].getName();
			if ("class".equals(name)) {
				continue; // No point in trying to set an object's class
			}
			if(names != null && !names.contains(name)){
				continue;
			}
			if (PropertyUtils.isReadable(orig, name)
				&& PropertyUtils.isWriteable(dest, name)) {
				try {
					Object value = PropertyUtils.getSimpleProperty(orig, name);
					if (value != null) {
						copyProperty(dest, name, value);
					}
				} catch (NoSuchMethodException e) {
					; // Should not happen
				}
			}
		}
	}
	
	public static void copyProperty(Object bean, String name, Object value)
		throws IllegalAccessException, InvocationTargetException {
		Object target = bean;
		String propName = name;
		PropertyDescriptor descriptor = null;
		try {
			descriptor = PropertyUtils.getPropertyDescriptor(target, name);
			if (descriptor == null)
				return;
		} catch (NoSuchMethodException e) {
			return;
		}
		Class type = descriptor.getPropertyType();
		if (type == null) {
			return;
		}
		Converter converter = ConvertUtils.lookup(type);
		if (converter != null) {
			value = converter.convert(type, value);
		}
		try {
			PropertyUtils.setSimpleProperty(target, propName, value);
		} catch (NoSuchMethodException e) {
			throw new InvocationTargetException(e, "Cannot set " + propName);
		}
	}
	
}
